import unittest

from ExercisesAdvanced.Debug_Source import Dict


def rerun(time=3):
    _time = time
    def onDecorator(func):
        def onCall(*args, **kwargs):
            nonlocal _time
            while _time > 0:
                try:
                    print('第{0}次执行用例[{1}]'.format(time-_time+1, func.__name__))
                    result = func(*args, **kwargs)
                    return result
                except Exception as e:
                    _time -= 1
                    if _time == 0:
                        print('到达{0}次执行上限，不通过，抛出异常{1}'.format(time, e))
                        raise e
        return onCall
    return onDecorator



class TestDict(unittest.TestCase):

    ExcpStack = []

    def my_assertEqual(self, first, second, msg=None):
        try:
            self.assertEqual(first, second, msg=msg)
        except AssertionError as e:
            self.ExcpStack.append(e)

    def my_assertNotEqual(self, first, second, msg=None):
        try:
            self.assertNotEqual(first, second, msg=msg)
        except AssertionError as e:
            self.ExcpStack.append(e)

    def raise_excp(self):
        if self.ExcpStack:
            excp_text = ' && '.join(str(x) for x in self.ExcpStack)
            self.ExcpStack.clear()
            raise AssertionError(excp_text)

    # @rerun()
    def test_init(self):
        d = Dict(a=1, b='test')
        self.my_assertEqual(d.a, 2)
        self.my_assertNotEqual(d.b, 'test')
        self.assertTrue(isinstance(d, dict))
        self.raise_excp()

    # @rerun()
    def test_key(self):
        d = Dict()
        d['key'] = 'value'
        self.my_assertEqual(d.key, 'value')

    def test_attr(self):
        d = Dict()
        d.key = 'value'
        self.assertTrue('key' in d)
        self.assertEqual(d['key'], 'value')

    def test_keyerror(self):
        d = Dict()
        with self.assertRaises(KeyError):
            value = d['empty']

    def test_attrerror(self):
        d = Dict()
        with self.assertRaises(AttributeError):
            value = d.empty

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(TestDict('test_init'))
    suite.addTest(TestDict('test_key'))
    suite.addTest(TestDict('test_attr'))
    suite.addTest(TestDict('test_keyerror'))
    suite.addTest(TestDict('test_attrerror'))
    runner = unittest.TextTestRunner()
    test_result = runner.run(suite)
    for k, v in vars(test_result).items():
        print(k, '>>', v)